/*
 *
 * Copyright (c) 2001-2016 泛微软件.
 * 泛微协同商务系统,版权所有.
 * 
 */
package weaver.sms;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.*;


import weaver.conn.*;
import weaver.general.*;
import weaver.hrm.resource.ResourceComInfo;
/**
 * 短信保存发送接口
 * @author HuangGuanGuan
 * Jun 20, 2017
 *
 */
public class SMSSaveAndSend extends BaseBean {
	/**
	 * 回复标识
	 */
    public static String REPLAY_CHAR = "R";
    private String message;       /*短信内容*/
    private String rechrmnumber; /*员工接收方手机号*/
    private String reccrmnumber; /*客户接收方手机号*/
    private String customernumber; /*自定义接收方手机号*/

    private String rechrmids; /*客户接收方id*/
    private String reccrmids; /*客户接收方id*/

    private String sendnumber;    /*发送方手机号*/
    private String messagestatus; /*短信当前的状态，0－待发，1－已发,2－接受*/
    private int requestid;     /*工作流触发时记录工作流ID*/
    private int userid;        /*发送者*/
    private String usertype;      /*发送者类型，1－内部用户*/
    private String messagetype;   /*消息的类型 0－发送消息，1－接受消息*/
    private String finishtime;    /*发送或接受日期*/
    /**
     * 短信签名
     */
    private String sign;
    /**
     * 签名位置
     */
    private String signPos;
    /**
     * 是否长短信
     */
    private boolean longSms;
    /**
     * 短信分割数
     */
    private int splitLength;
    /**
     * 短信发送方法
     */
    private SMSManager smsManager = null;
    /**
     * 构造函数
     */
    public SMSSaveAndSend() {
        smsManager = new SMSManager();
        reset();
    }
    /**
     * 重置参数
     */
    public void reset() {
        message = "";
        rechrmnumber = "";
        reccrmnumber="";
        customernumber="";
        sendnumber = "";
        rechrmids="";
        reccrmids="";
        messagestatus = "0";
        requestid = -1;
        userid = -1;
        usertype = "1";
        messagetype = "0";
        finishtime = "";
        sign="";
        longSms=false;
        splitLength=60;
    }
    /**
     * 年
     * @param dateStr
     * @return
     */
    public static String getYear(String dateStr) {
        if (dateStr != null && dateStr.length() > 0) {
            return dateStr.substring(0, dateStr.indexOf("-"));
        }
        return "";
    }
    /**
     * 月
     * @param dateStr
     * @return
     */
    public static String getMonth(String dateStr) {
        if (dateStr != null && dateStr.length() > 0) {
            String tempStr = dateStr.substring(dateStr.indexOf("-") + 1);
            return tempStr.substring(0, tempStr.indexOf("-"));
        }
        return "";
    }
    /**
     * 日
     * @param dateStr
     * @return
     */
    public static String getDay(String dateStr) {
        if (dateStr != null && dateStr.length() > 0) {
            String tempStr = dateStr.substring(dateStr.indexOf("-") + 1);
            tempStr = tempStr.substring(tempStr.indexOf("-") + 1);
            return tempStr.substring(0, 2);
        }
        return "";
    }

    /**
     * 
     * @return
     */
    public String getMessage() {
        return message;
    }
    /**
     * 设置短信发送内容
     * @param value
     */
    public void setMessage(String value) {
        message = value;
    }
    /**
     * 
     * @return
     */
    public String getRechrmnumber() {
        return rechrmnumber;
    }
    /**
     * 设置人员号码
     * @param value
     */
    public void setRechrmnumber(String value) {
        rechrmnumber = value;
    }
    /**
     * 
     * @return
     */
    public String getReccrmnumber() {
        return reccrmnumber;
    }
    /**
     * 设置客户联系人号码
     * @param reccrmnumber
     */
    public void setReccrmnumber(String reccrmnumber) {
        this.reccrmnumber = reccrmnumber;
    }
    /**
     * 
     * @return
     */
    public String getRechrmids() {
        return rechrmids;
    }
    /**
     * 设置人员id
     * @param rechrmids
     */
    public void setRechrmids(String rechrmids) {
        this.rechrmids = rechrmids;
    }
    /**
     * 
     * @return
     */
    public String getReccrmids() {
        return reccrmids;
    }
    /**
     * 设置客户id
     * @param reccrmids
     */
    public void setReccrmids(String reccrmids) {
        this.reccrmids = reccrmids;
    }
    /**
     * 
     * @return
     */
    public String getSendnumber() {
        return sendnumber;
    }
    /**
     * 
     * @param value
     */
    public void setSendnumber(String value) {
        sendnumber = value;
    }
    /**
     * 
     * @return
     */
    public String getMessagestatus() {
        return messagestatus;
    }
    /**
     * 
     * @param value
     */
    public void setMessagestatus(String value) {
        messagestatus = value;
    }
    /**
     * 
     * @return
     */
    public int getRequestid() {
        return requestid;
    }
    /**
     * 设置流程id
     * @param value
     */
    public void setRequestid(int value) {
        requestid = value;
    }
    /**
     * 
     * @return
     */
    public int getUserid() {
        return userid;
    }
    /**
     * 设置发送人id
     * @param value
     */
    public void setUserid(int value) {
        userid = value;
    }
    /**
     * 
     * @return
     */
    public String getUsertype() {
        return usertype;
    }
    /**
     * 
     * @param value
     */
    public void setUsertype(String value) {
        usertype = value;
    }
    /**
     * 设置自定义号码, 多个号码使用英文逗号分割
     * @param customernumber
     */
    public void setCustomernumber(String customernumber) {
        this.customernumber = customernumber;
    }
    /**
     * 获取当前时间
     * @return
     */
    public String getDateTime() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String mDateTime = formatter.format(cal.getTime());
        return formatDateTime(mDateTime);
    }

    /**
     * 根据手机号查找客户手机用户的id
     * @param number
     * @return
     */
    public static String getCrmId(String number) {
        String sql = "select t3.id from CRM_CustomerInfo  t1,CRM_CustomerContacter t3  where t3.customerid=t1.id and t3.mobilephone='" + number + "'";
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        if (rs.next()) {
            return rs.getString("id");
        }
        return "";
    }

    /**
     * 根据手机号查找员工手机用户的id
     * @param number
     * @return
     */
    public static String getHrmId(String number) {
        String sql = "select id from HrmResource where mobile='" + number + "'";
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        if (rs.next()) {
            return rs.getString("id");
        }
        return "";
    }

    /**
     * 时间格式化
     * @param dateTime
     * @return
     */
    public static String formatDateTime(String dateTime) {
        if (dateTime == null || dateTime.trim().equals("")) {
            return dateTime;
        }
        dateTime = dateTime.trim();
        String retStr = "";
        String temStr = "";
        int index = dateTime.indexOf("-");
        if (index != -1) {
            temStr = dateTime.substring(0, index);
            dateTime = dateTime.substring(index + 1);
            if (temStr.length() < 4) {
                retStr += "20" + temStr;
            } else {
                retStr += temStr;
            }
        }
        index = dateTime.indexOf("-");
        if (index != -1) {
            temStr = dateTime.substring(0, index);
            dateTime = dateTime.substring(index + 1);
            if (temStr.length() < 2) {
                retStr += "-0" + temStr;
            } else {
                retStr += "-" + temStr;
            }
        }
        index = dateTime.indexOf(" ");
        if (index != -1) {
            temStr = dateTime.substring(0, index);
            dateTime = dateTime.substring(index + 1);
            if (temStr.length() < 2) {
                retStr += "-0" + temStr;
            } else {
                retStr += "-" + temStr;
            }
        }
        index = dateTime.indexOf(":");
        if (index != -1) {
            temStr = dateTime.substring(0, index);
            dateTime = dateTime.substring(index + 1);
            if (temStr.length() < 2) {
                retStr += " 0" + temStr;
            } else {
                retStr += " " + temStr;
            }
        }
        index = dateTime.indexOf(":");
        if (index != -1) {
            temStr = dateTime.substring(0, index);
            dateTime = dateTime.substring(index + 1);
            if (temStr.length() < 2) {
                retStr += ":0" + temStr;
            } else {
                retStr += ":" + temStr;
            }
        }
        temStr = dateTime;
        if (temStr.length() < 2) {
            retStr += ":0" + temStr;
        } else {
            retStr += ":" + temStr;
        }

        return retStr;
    }

    /**
     * 程序调用,线程发送
     * @return
     */
    public boolean send() {
        boolean ret = true;
        BaseBean bb=new BaseBean();
        if ((rechrmids == null || "".equals(rechrmids)) && (reccrmnumber == null || "".equals(reccrmnumber)) && (customernumber == null || "".equals(customernumber))) {
            //return false;
        }

        if (smsManager.isValid()) {
        	//获取系统短信签名,是否是长短信,分割字数
        	sign=Util.null2String(SmsCache.getSmsSet().getSign());
        	bb.writeLog("sign=="+sign);
        	signPos=SmsCache.getSmsSet().getSignPos();
            bb.writeLog("sign=="+signPos);
        	longSms="1".equals(Util.null2String(SmsCache.getSmsSet().getLongSms()));
        	bb.writeLog("longSms="+longSms);
        	splitLength=SmsCache.getSmsSet().getSplitLength();
        	//调用线程发送
        	startSend();	
        } else {
            ret = false;
        }
        return ret;

    }
    
    /**
     * 页面发送,实时发送
     * @return
     */
    public boolean pageSend(){
    	boolean ret = true;
        if ((rechrmids == null || "".equals(rechrmids)) && (reccrmnumber == null || "".equals(reccrmnumber)) && (customernumber == null || "".equals(customernumber))) {
            //return false;
        }

        if (smsManager.isValid()) {
        	//获取系统短信签名,是否是长短信,分割字数
        	sign=Util.null2String(SmsCache.getSmsSet().getSign());
        	signPos=SmsCache.getSmsSet().getSignPos();
        	longSms="1".equals(Util.null2String(SmsCache.getSmsSet().getLongSms()));
        	splitLength=SmsCache.getSmsSet().getSplitLength();
            //兼容多种短信分割
            customernumber=Util.null2String(customernumber);
            customernumber=customernumber.replace("，",",").replace("；",",").replace(";",",").replace("、",",");

            StringTokenizer stRecCrmNumber = new StringTokenizer(reccrmnumber, ",");
            StringTokenizer stCustomerNumber = new StringTokenizer(customernumber, ",");

            StringTokenizer stRecHrmIds = new StringTokenizer(rechrmids, ",");
            StringTokenizer stRecCrmIds = new StringTokenizer(reccrmids, ",");
            String number = "";
            String id = "";
            ResourceComInfo rci=null;
            try{
            	rci = new ResourceComInfo();
            }catch(Exception e){
            	e.printStackTrace();
            }
            RecordSet rs=new RecordSet();
	        while (stRecHrmIds.hasMoreTokens()) {
	        	//number = stRecHrmNumber.nextToken();
	            id = stRecHrmIds.nextToken();
	            if(null!=rci){
	            	number=rci.getMobile(id);
	            	if(number==null||"".equals(number)){
                        rs.writeLog("人员("+id+")通过缓存类获取手机号码失败");
                    }
	            }else{
	                rs.writeLog("从缓存类获取手机号码失败，通过人力资源表获取手机号码");
	                rs.execute("select mobile from hrmresource where id="+id);
	                if(rs.next()){
	                	number=rs.getString("mobile");
	                }
	            }
	            number=checkPhoneNum(number);
	            String[] numbers=number.split(",");
	            for(int i=0;i<numbers.length;i++){
	            	number=numbers[i];
	                if(!number.isEmpty()){
	                	if (send(number, id, "1") == false) {
	                		ret = false;
	                	}
	                }
	            }
	        }
			
	        while (stRecCrmNumber.hasMoreTokens()) {
                number = stRecCrmNumber.nextToken();
                id = stRecCrmIds.nextToken();
                //System.out.println("number:" + number);
                //System.out.println("id = " + id);
                //System.out.println("usertype = " + 1);
                if (number.equals("")) {
                    continue;
                }
                if (send(number, id, "2") == false) {
                    ret = false;
                }
            }

            while (stCustomerNumber.hasMoreTokens()) {
                number = stCustomerNumber.nextToken();
                String userType = "0";
                id = SMSSaveAndSend.getHrmId(number);
                if (!id.equals("")) {
                    userType = "1";
                } else {
                    id = SMSSaveAndSend.getCrmId(number);
                    if (!id.equals("")) {
                        userType = "2";
                    } else {
                        id = "0";
                    }
                }

                //System.out.println("number:" + number);
                //System.out.println("id = " + id);
                //System.out.println("usertype = " + userType);
                if (number.equals("")) {
                    continue;
                }
                if (send(number, id, userType) == false) {
                    ret = false;
                }
            }
			
            
        } else {
            ret = false;
        }
        return ret;
    }
    /**
     * 重发
     * @param ids
     * @return
     */
    public boolean reSend(String ids) {
        boolean ret = true;
        //对选择的 待发和发送失败的进行重发
        String sql = "select id,message,recievenumber,userid from SMS_Message where id in(" + ids + ") and (messagestatus='0' or messagestatus='3')";
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        rs.execute(sql);
        
        sign=Util.null2String(SmsCache.getSmsSet().getSign());
    	longSms="1".equals(Util.null2String(SmsCache.getSmsSet().getLongSms()));
    	splitLength=SmsCache.getSmsSet().getSplitLength();
    	
        while(rs.next()){
        	int smsid=rs.getInt("id");
        	String message=rs.getString("message");
        	String toNumber=rs.getString("recievenumber");
        	int userid=rs.getInt("userid");
        	
        	//更新状态为待发
        	rs1.execute("Update SMS_Message Set messagestatus='0' where id=" + smsid);
        	
        	//发送 
        	if(longSms){//是否长短信
        		if (!smsManager.sendDBSMS(smsid, userid, toNumber, "0".equals(signPos)?sign+message:message+sign)) 
        		{
        			ret = false;
        		}
        	}else{//需要拆分,考虑拆分后每条短信的签名
        		
        		int signlength=sign.length();//签名长度
        		int realSplitLength=splitLength-signlength;//去除签名长度
        		int realLength=realSplitLength-4;//去除分割前缀长度,(1) 以防出现(10) 默认减去4位
        		if(message.length() > realSplitLength){//判断是否要分割
        			for(int i = 0; i < (message.length() / realLength) + 1; i++)
        			{	
        				int endLength = (i + 1) * realLength;
        				if(endLength > message.length())
        				{
        					endLength = message.length();
        				}
        				
        				String toMessage ="0".equals(signPos)?sign+ "(" + (i + 1) + ")" + message.substring(i * realLength, endLength):"(" + (i + 1) + ")" + message.substring(i * realLength, endLength)+sign;
            			//System.out.println("$$$" + toMessage);
        				if (!smsManager.sendDBSMS(smsid, userid, toNumber, toMessage)) 
        				{
        					ret = false;
        					break;
        				}
        			}
        		}else{
        			if (!smsManager.sendDBSMS(smsid, userid, toNumber, "0".equals(signPos)?sign+message:message+sign)) 
        			{
        				ret = false;
        			}
        		}
        	}
        	
        }
        
        return ret;

    }
    
    /**
     * 线程发送
     */
    private void startSend() 
	{
    	ThreadPoolUtil.getThreadPool("SMS", "5").execute((new Runnable() 
		{
			public void run() 
			{
	            StringTokenizer stCustomerNumber = new StringTokenizer(customernumber, ",");
	            StringTokenizer stRecHrmIds = new StringTokenizer(rechrmids, ",");
	            StringTokenizer stRecCrmIds = new StringTokenizer(reccrmids, ",");
	            
	            String number = "";
	            String id = "";
	            ResourceComInfo rci;
				try {
					rci = new ResourceComInfo();
				
		            while (stRecHrmIds.hasMoreTokens()) {
		                //number = stRecHrmNumber.nextToken();
		                id = stRecHrmIds.nextToken();
		                number=rci.getMobile(id);
		                number=checkPhoneNum(number);
		                String[] numbers=number.split(",");
		                for(int i=0;i<numbers.length;i++){
		                	number=numbers[i];
		                	if (number.equals("")) {
			                    continue;
			                }
			                send(number, id, "1");
		                }
		            }
		            //System.out.println("**********");
		            while (stRecCrmIds.hasMoreTokens()) {
						number="";
		                id = stRecCrmIds.nextToken();
		                RecordSet rs=new RecordSet();
		                rs.execute("select * from CRM_CustomerContacter where customerid="+id);
		                while(rs.next()){
		                	if(!number.isEmpty()){
		                		number+=",";
		                	}
		                	number+=rs.getString("mobilephone");
		                }
		                number=checkPhoneNum(number);
		                String[] numbers=number.split(",");
		                for(int i=0;i<numbers.length;i++){
		                	number=numbers[i];
		                	if (number.equals("")) {
			                    continue;
			                }
			                send(number, id, "2");
		                }
		            }

		            while (stCustomerNumber.hasMoreTokens()) {
		                number = stCustomerNumber.nextToken();
		                number=checkPhoneNum(number);
		                String userType = "0";
		                id = SMSSaveAndSend.getHrmId(number);
		                if (!id.equals("")) {
		                    userType = "1";
		                } else {
		                    id = SMSSaveAndSend.getCrmId(number);
		                    if (!id.equals("")) {
		                        userType = "2";
		                    } else {
		                        id = "0";
		                    }
		                }
		                if (number.equals("")) {
		                    continue;
		                }
		                send(number, id, userType);
		            }
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}));
	}
    /**
     * 发送短信
     * @param toNumber
     * @param toId
     * @param toUserType
     * @return
     */
    private boolean send(String toNumber, String toId, String toUserType) {
        boolean ret = true;
        RecordSet rs = new RecordSet();
        int smsid = getSmsId();
        char separator = Util.getSeparator();
        String dbMessage = null;
        try {
        	//message 已经加过前后缀提醒,短信签名不加,方便重发
            message = message.replaceAll("\n"," ");
        	message = Util.formatMultiLang(message,7+"");
            dbMessage = message;//(new String(message.getBytes("GBK"),"8859_1"));
            message=message.replaceAll("&quot;","\"");
        	message=message.replaceAll("&nbsp;"," ");
        	message=message.replaceAll("&lt;","<");
        	message=message.replaceAll("&gt;",">");
        } catch (Exception ex) {
            writeLog("send(......) error");
        }
        String curDataTime = getDateTime();
        finishtime=SMSSaveAndSend.formatDateTime(curDataTime);
        String smsyear=SMSSaveAndSend.getYear(SMSSaveAndSend.formatDateTime(curDataTime));
        String smsmonth=SMSSaveAndSend.getMonth(SMSSaveAndSend.formatDateTime(curDataTime));
        String smsday=SMSSaveAndSend.getDay(SMSSaveAndSend.formatDateTime(curDataTime));
        
        String para = "" +
                smsid + separator +
                dbMessage + separator +
                toNumber + separator +
                sendnumber + separator +
                "0" + separator +
                requestid + separator +
                userid + separator +
                usertype + separator +
                "2" + separator +
                finishtime + separator +
                smsyear + separator +
                smsmonth + separator +
                smsday + separator +
                "0" + separator +
                toId + separator +
                toUserType;
        //System.out.println("para = " + para);
        rs.executeProc("SMS_Message_Insert", para);
        
        
        if(longSms){//是否长短信
        	if (!smsManager.sendDBSMS(smsid, userid, toNumber, "0".equals(signPos)?sign+message:message+sign)) 
            {
                ret = false;
            }
        }else{//需要拆分,考虑拆分后每条短信的签名
        	
        	int signlength=sign.length();//签名长度
        	int realSplitLength=splitLength-signlength;//去除签名长度
        	int realLength=realSplitLength-4;//去除分割前缀长度
        	if(message.length() > realSplitLength){//判断是否要分割
        		for(int i = 0; i < (message.length() / realLength) + 1; i++)
        		{	
        			int endLength = (i + 1) * realLength;
        			if(endLength > message.length())
        			{
        				endLength = message.length();
        			}
        			
        			String toMessage ="0".equals(signPos)?sign+ "(" + (i + 1) + ")" + message.substring(i * realLength, endLength):"(" + (i + 1) + ")" + message.substring(i * realLength, endLength)+sign;
        			//System.out.println("$$$" + toMessage);
        			if (!smsManager.sendDBSMS(smsid, userid, toNumber, toMessage)) 
        			{
        				ret = false;
        				break;
        			}
        		}
        	}else{
        		if (!smsManager.sendDBSMS(smsid, userid, toNumber, "0".equals(signPos)?sign+message:message+sign)) 
        		{
        			ret = false;
        		}
        	}
        }
        
        return ret;
    }
    /**
     * 获取smsId
     * @return
     */
    public synchronized static int getSmsId(){
    	RecordSet rs = new RecordSet();
        rs.executeProc("SequenceIndex_SelectSmsid", "");
        int smsid = -1;
        if (rs.next()) {
            smsid = Util.getIntValue(rs.getString(1));
        }
        return smsid;
    }
    /**
     * 正则解析手机号码
     * 去除减号，保留连续数字作为手机号码，其他字符作为多个号码的分隔
     * @param num
     * @return
     */
    public static String checkPhoneNum(String num){
    	if(num.isEmpty()){
    		return "";
    	}
    	num=num.replace("-", "");
		Pattern pattern = Pattern.compile("(?:[0-9]\\d*)"); 
		Matcher matcher = pattern.matcher(num); 
		StringBuffer bf = new StringBuffer(64); 
		while (matcher.find()) { 
			bf.append(matcher.group()).append(","); 
		} 
		int len = bf.length(); 
		if (len > 0) { 
			bf.deleteCharAt(len - 1); 
		}
		return bf.toString();
    }
}